<template>
    <div>
        <Edit :is-detail="type === 'detail'" :ruleForm="ruleForm" ref="editForm" type="16" />
        <div class="submitBtn">
          <el-button v-if="type !== 'detail'" class="mt10" type="primary" @click="onSubmit">保 存</el-button>
        </div>
    </div>
</template>

<script>
import Edit from '@/views/components/edit.vue'
import { addMedia } from '@/api/index'
import { getMedia, editMedia } from '@/api/news'
export default {
    name: 'AddMedia',
    components: { Edit },
    data() {
        return {
            id: null,
            type: null,
            ruleForm: {}
        }
    },
    async created() {
        if (this.$route.query.id) {
            this.id = this.$route.query.id
            this.type = this.$route.query.type || 'add'
            let res = await getMedia({ id: this.$route.query.id })
            this.ruleForm = res.data
        }
    },
    methods: {
        async onSubmit() {
            let form = await this.$refs.editForm.validate()
            let newForm = {
                title: form.title,
                category_id: form.category_id,
                url: form.url,
                cover_pic: form.cover_pic,
            }
            this.id !== null && (newForm.id = this.id)
            let fetchApi = this.id === null ? addMedia : editMedia
            await fetchApi(newForm)
            this.$message({
                type: 'success',
                message: '成功'
            })
            this.$router.push('/media')
        }
    }
}
</script>
